package com.yzt.dynamicmodule.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.manu.mdatepicker.MDatePickerDialog;
import com.yzt.zhuju.arouter.RouterDynamic;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.dialog1.BaseSelectDialog;
import com.yzt.zhuju.dialog1.SelectEmotionDialog;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.user.GameAddEvent;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.game.GameCreateBean;
import com.yzt.zhuju.network.entity.game.GameDetailBean;
import com.yzt.zhuju.network.entity.sysConfig.AliOSSCredentialBean;
import com.yzt.zhuju.utils.DefaultCropFileEngine;
import com.yzt.zhuju.utils.GlideImageEngine;
import com.yzt.zhuju.utils.ImageUpLoadUtils;
import com.yzt.zhuju.utils.McImageCompressEngine;
import com.yzt.zhuju.utils.TimeUtils;
import com.yzt.zhuju.utils.map.BdLocationUtil;
import com.yzt.zhuju.widget.tuiview.TUITextView;
import com.yzt.zhuju.widget.widget.ImageLoadManger;
import com.yzt.dynamicmodule.R;
import com.yzt.p_base.utils.ToastUtil;

import java.util.ArrayList;

/**
 * 作者：bobwang
 * 创建时间：2023-11-19 20:05:48
 * 描述：新增组局
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterDynamic.ACTIVITY_GAME_ADD)
public class GameAddActivity extends BaseActivity implements View.OnClickListener {

    private final int MY_PERMISSIONS_REQUEST_LOCATION = 9999;

    private LinearLayout ll_add;
    private ImageView img_cover;
    private ImageView img_cover_del;

    private EditText et_title;
    private EditText et_content;
    private TextView tv_content_count;

    private TextView tv_start_time;
    private TextView tv_end_time;
    private TextView tv_address;
    private EditText et_address;

    private ImageView img_boy_del;
    private TextView tv_boy_num;
    private ImageView img_boy_add;

    private ImageView img_girl_del;
    private TextView tv_girl_num;
    private ImageView img_girl_add;

    private EditText et_price;
    private TextView tv_place_pay;
    private TextView tv_place_income;

    private TUITextView tv_post;

    private int girlCount = 1;
    private int boyCount = 1;
    private int intPay = 0;
    private int intIncome = 0;
    private String activityFileUrl;
    private String cover;

    private AliOSSCredentialBean aliOSSCredentialBean;

    private String gameId;

    public static void startSelf(Context activity, String extraId) {
        activity.startActivity(new Intent(activity, GameAddActivity.class)
                .putExtra("extra_id", extraId));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_game_add;
    }

    @Override
    public void installViews() {
        mTitleBar.setTitle("发起组局");

        gameId = getIntent().getStringExtra("extra_id");

        // 初始化页面监听
        initViewClick();

        // 加载定位
        initPermission();

        // 签名
        getAliSign();

        // 获取游戏详情
        getGameDetail();
    }

    /**
     * 权限初始化
     */
    private void initPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                // 方法帮助应用判断是否需要向用户解释为什么需要某个权限，并在适当的时候进行解释和再次请求。
            } else {
                //请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
        } else {
            // 权限满足
            initLocationOption();
        }
    }

    private LatLng latLng;

    /**
     * 获取定位信息
     */
    private void initLocationOption() {

        if (!checkGPSIsOpen(mActivity)) {
            ToastUtil.showMessage("请打开GPS定位服务");
        }

        BdLocationUtil.getInstance().requestLocation(new BdLocationUtil.MyLocationListener() {
            @Override
            public void myLocation(BDLocation location) {
                latLng = BdLocationUtil.bd2gd(location.getLatitude(), location.getLongitude());
                latitudeValue = latLng.latitude + "";
                longitudeValue = latLng.longitude + "";
                cityCode = location.getCityCode();
                city = location.getCity();
            }
        });
    }

    public static boolean checkGPSIsOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_LOCATION) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 得到了权限
            } else {
                // 没有得到权限
            }
        }
    }

    /**
     * 获取游戏详情
     */
    private void getGameDetail() {
        if (gameId != null) {
            JSONObject json = new JSONObject();
            json.put("activityId", gameId);
            BizLayer.getInstance().getDynamicModule().getGameDetail(json, new AresSubscriber<GameDetailBean>() {
                @Override
                protected void onSuccess(GameDetailBean bean) {
                    img_cover.setVisibility(View.VISIBLE);
                    img_cover_del.setVisibility(View.VISIBLE);
                    ll_add.setVisibility(View.GONE);
                    ImageLoadManger.loadIv(mActivity, bean.getCover(), img_cover, R.mipmap.default_photo);
                    et_title.setText(bean.getActivitySubject());
                    et_content.setText(bean.getDsc());
                    tv_content_count.setText(bean.getActivitySubject().length() + "/300");
                    tv_start_time.setText(bean.getStartTime());
                    tv_end_time.setText(bean.getEndTime());
                    tv_address.setText(bean.getAddress());
                    et_address.setText(bean.getLocation());
                    tv_boy_num.setText(bean.getMaleNum() + "");
                    tv_girl_num.setText(bean.getFemaleNum() + "");
                    et_price.setText(bean.getUnitPrice());
                    String payerType = bean.getPayerType() == 1 ? "男士付款" : (bean.getPayerType() == 1 ? "女士付款" : "发起人付款");
                    tv_place_pay.setText(payerType);
                    String payeeType = bean.getPayeeType() == 1 ? "男士收款" : (bean.getPayeeType() == 1 ? "女士收款" : "所有玩家AA收款");
                    tv_place_income.setText(payeeType);
                    intPay = bean.getPayerType();
                    intIncome = bean.getPayeeType();
                    activityFileUrl = bean.getCover();
                    cover = bean.getCover();
                    tv_post.setText("编辑");

                    tv_address.setEnabled(false);
                    tv_address.setTextColor(Color.parseColor("#7d7d7d"));
                    et_address.setEnabled(false);
                    et_address.setTextColor(Color.parseColor("#7d7d7d"));
                    img_boy_del.setEnabled(false);
                    img_boy_add.setEnabled(false);
                    img_girl_del.setEnabled(false);
                    img_girl_add.setEnabled(false);
                    et_price.setEnabled(false);
                    et_price.setTextColor(Color.parseColor("#7d7d7d"));
                    tv_place_pay.setEnabled(false);
                    tv_place_pay.setTextColor(Color.parseColor("#7d7d7d"));
                    tv_place_income.setEnabled(false);
                    tv_place_income.setTextColor(Color.parseColor("#7d7d7d"));
                    tv_boy_num.setTextColor(Color.parseColor("#7d7d7d"));
                    tv_girl_num.setTextColor(Color.parseColor("#7d7d7d"));
                }
            });
        }
    }

    /**
     * 视图监听
     */
    private void initViewClick() {
        ll_add = findViewById(R.id.ll_add);
        ll_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(mActivity)
                        .openGallery(SelectMimeType.ofAll())
                        .setImageEngine(GlideImageEngine.Companion.getInstance())
                        .setCompressEngine(McImageCompressEngine.Companion.getInstance())
                        .setCropEngine(new DefaultCropFileEngine())
                        .setMaxVideoSelectNum(1)
                        .setMaxSelectNum(1)
                        .setFilterVideoMaxSecond(30)
                        .isDirectReturnSingle(true)
                        .isDisplayCamera(false)
                        .isOpenClickSound(false)
                        .isFastSlidingSelect(true)
                        .isPreviewFullScreenMode(true)
                        .isPreviewZoomEffect(true)
                        .isPreviewImage(true)
                        .isMaxSelectEnabledMask(true)
                        .isGif(false)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        img_cover = findViewById(R.id.img_cover);
        img_cover_del = findViewById(R.id.img_cover_del);
        img_cover_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_cover.setVisibility(View.GONE);
                img_cover_del.setVisibility(View.GONE);
                ll_add.setVisibility(View.VISIBLE);
            }
        });

        et_title = findViewById(R.id.et_title);
        et_content = findViewById(R.id.et_content);
        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String count = et_content.getText().toString().trim();
                tv_content_count.setText(count.length() + "/300");
            }
        });
        tv_content_count = findViewById(R.id.tv_content_count);

        tv_start_time = findViewById(R.id.tv_start_time);
        tv_start_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MDatePickerDialog dialog = new MDatePickerDialog.Builder(mActivity, tv_start_time.getText().toString())
                        .setCanceledTouchOutside(true)
                        .setGravity(Gravity.BOTTOM)
                        .setSupportTime(true)
                        .setTwelveHour(true)
                        .setCanceledTouchOutside(false)
                        .setOnlyYearMonth(false)
                        .setOnDateResultListener(new MDatePickerDialog.OnDateResultListener() {
                            @Override
                            public void onDateResult(long date) {
                                tv_start_time.setText(TimeUtils.yyyymmddhhmm(date));
                            }
                        }).build();
                dialog.setMinYear(2024);
                dialog.setMaxYear(2027);
                dialog.show();
            }
        });
        tv_end_time = findViewById(R.id.tv_end_time);
        tv_end_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MDatePickerDialog dialog = new MDatePickerDialog.Builder(mActivity, tv_start_time.getText().toString())
                        .setCanceledTouchOutside(true)
                        .setGravity(Gravity.BOTTOM)
                        .setSupportTime(true)
                        .setTwelveHour(true)
                        .setCanceledTouchOutside(false)
                        .setOnlyYearMonth(false)
                        .setOnDateResultListener(new MDatePickerDialog.OnDateResultListener() {
                            @Override
                            public void onDateResult(long date) {
                                tv_end_time.setText(TimeUtils.yyyymmddhhmm(date));
                            }
                        }).build();
                dialog.setMinYear(2024);
                dialog.setMaxYear(2027);
                dialog.show();
            }
        });
        tv_address = findViewById(R.id.tv_address);
        tv_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, GameAddCityActivity.class);
                intent.putExtra("extra_id", city);
                intent.putExtra("extra_latitude", latLng.latitude);
                intent.putExtra("extra_longitude", latLng.longitude);
                startActivityForResult(intent, 3);
            }
        });
        et_address = findViewById(R.id.et_address);

        img_boy_del = findViewById(R.id.img_boy_del);
        img_boy_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boyCount--;
                if (boyCount < 0) {
                    boyCount = 0;
                }
                tv_boy_num.setText(boyCount + "");
            }
        });
        tv_boy_num = findViewById(R.id.tv_boy_num);
        img_boy_add = findViewById(R.id.img_boy_add);
        img_boy_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boyCount++;
                tv_boy_num.setText(boyCount + "");
            }
        });

        img_girl_del = findViewById(R.id.img_girl_del);
        img_girl_del.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                girlCount--;
                if (girlCount < 0) {
                    girlCount = 0;
                }
                tv_girl_num.setText(girlCount + "");
            }
        });
        tv_girl_num = findViewById(R.id.tv_girl_num);
        img_girl_add = findViewById(R.id.img_girl_add);
        img_girl_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                girlCount++;
                tv_girl_num.setText(girlCount + "");
            }
        });

        et_price = findViewById(R.id.et_price);
        tv_place_pay = findViewById(R.id.tv_place_pay);
        tv_place_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> list = new ArrayList<>();
                list.add("男士付");
                list.add("女士付");
                list.add("我付");
                SelectEmotionDialog emotionDialog = new SelectEmotionDialog(mActivity, tv_place_pay.getText().toString(), list);
                emotionDialog.setOnSelectListener(new BaseSelectDialog.OnSelectListener<String>() {
                    @Override
                    public void onSelect(String data, int index) {
                        tv_place_pay.setText(data);
                        intPay = index + 1;
                    }
                });
                emotionDialog.show();
            }
        });
        tv_place_income = findViewById(R.id.tv_place_income);
        tv_place_income.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> list = new ArrayList<>();
                list.add("男士收款");
                list.add("女士收款");
                list.add("所有玩家AA收款");
                SelectEmotionDialog emotionDialog = new SelectEmotionDialog(mActivity, tv_place_income.getText().toString(), list);
                emotionDialog.setOnSelectListener(new BaseSelectDialog.OnSelectListener<String>() {
                    @Override
                    public void onSelect(String data, int index) {
                        tv_place_income.setText(data);
                        intIncome = index + 1;
                    }
                });
                emotionDialog.show();
            }
        });

        tv_post = findViewById(R.id.tv_post);
        tv_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postGame();
            }
        });
    }

    /**
     * 获取 ali oss 签名信息
     */
    public void getAliSign() {
        BizLayer.getInstance().getSystemModule().getAliSign(new AresSubscriber<AliOSSCredentialBean>() {
            @Override
            protected void onSuccess(AliOSSCredentialBean data) {
                aliOSSCredentialBean = data;
                ImageUpLoadUtils.getInstance().init(GameAddActivity.this, aliOSSCredentialBean);
                Log.e("", "TeacherRegisterPresenterImpl-->我获得了ali签名信息");
            }
        });
    }

    private String latitudeValue;

    private String longitudeValue;

    private String cityCode;

    private String city;

    private void postGame() {

        JSONObject json = new JSONObject();

        json.put("activityId", gameId);

        json.put("activityFileUrl", activityFileUrl);
        if (activityFileUrl == null || activityFileUrl.equals("")) {
            showToast("请上传组局封面");
            return;
        }

        // 活动附件类型（图片，视频 [ 1：图片，2：视频 ]
        if (activityFileUrl.endsWith(".mp4")) {
            json.put("activityFileType", 2);
        } else {
            json.put("activityFileType", 1);
        }
        json.put("cover", cover);

        json.put("lat", latitudeValue);
        json.put("lon", longitudeValue);

        String title = et_title.getText().toString();
        if (title.equals("")) {
            showToast("请输入标题");
            return;
        }
        json.put("activitySubject", title);

        String content = et_content.getText().toString();
        if (content.equals("")) {
            showToast("请输入内容");
            return;
        }
        json.put("dsc", content);

        String startTime = tv_start_time.getText().toString();
        if (startTime.equals("")) {
            showToast("请选择开始时间");
            return;
        }
        json.put("startTime", startTime);

        String endTime = tv_end_time.getText().toString();
        if (endTime.equals("")) {
            showToast("请选择结束时间");
            return;
        }
        json.put("endTime", endTime);

        String location = tv_address.getText().toString();
        if (location.equals("")) {
            showToast("请选择组局地址");
            return;
        }
        json.put("location", location);
        json.put("cityCode", cityCode);

        String address = et_address.getText().toString();
        if (address.equals("")) {
            showToast("请输入详细地址");
            return;
        }
        json.put("address", address);

        String boyCount = tv_boy_num.getText().toString();
        json.put("maleNum", boyCount);

        String girlCount = tv_girl_num.getText().toString();
        json.put("femaleNum", girlCount);

        String unitPrice = et_price.getText().toString();
        if (unitPrice.equals("")) {
            showToast("请输入场地使用费");
            return;
        }
        json.put("unitPrice", unitPrice);

        // 付款人类型 （谁付款 [ 1：男士付款，2：女士付款，3：我付款 ]
        if (intPay == 0) {
            showToast("请选择场地使用费付款");
            return;
        }
        json.put("payerType", intPay);
        // 收款人类型 （谁收款 [ 1：男士收款，2：女士收款，3：所有玩家AA收款 ]
        if (intPay == 0) {
            showToast("请选择场地使用费收款");
            return;
        }
        json.put("payeeType", intIncome);

        BizLayer.getInstance().getDynamicModule().createGame(json, new AresSubscriber<GameCreateBean>() {
            @Override
            protected void onSuccess(GameCreateBean bean) {
                ToastUtil.showMessage("发布组局成功！");
                RxBus.getDefault().post(new GameAddEvent());
                finish();
            }

            @Override
            protected void onError(int code, String info) {
                super.onError(code, info);
                ToastUtil.showMessage(info);
            }

            @Override
            protected void onFinallyEnd() {
                super.onFinallyEnd();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_CANCELED) {
            return;
        }

        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {

                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                String picturePath = result.get(0).getRealPath();

                if (aliOSSCredentialBean == null) {
                    runOnUiThread(() -> {
                        showToast("获取照片签名异常，请重新选择照片");
                        getAliSign();
                    });
                } else {

                    showMProgress();

                    img_cover.setVisibility(View.VISIBLE);
                    img_cover_del.setVisibility(View.VISIBLE);
                    ll_add.setVisibility(View.GONE);
                    ImageLoadManger.loadIv(mActivity, picturePath, img_cover);

                    String time;
                    if (picturePath.equals("mp4") || picturePath.equals("MP4")) {
                        time = System.currentTimeMillis() + ".mp4";
                    } else {
                        time = System.currentTimeMillis() + ".png";
                    }

                    ImageUpLoadUtils.getInstance().asyncUpLoad(time, picturePath, new ImageUpLoadUtils.OnAsyncUpLoadListener() {

                        @Override
                        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                        }

                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result, String directory) {
                            closeProgress();
                            cover = directory + request.getObjectKey();
                            activityFileUrl = cover;
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            showToast("上传失败");
                            closeProgress();
                        }
                    });
                }
            }
        }

        if (requestCode == 3 && resultCode == RESULT_OK) {
            PoiInfo bean = data.getParcelableExtra("extra_data");
            latitudeValue = bean.getLocation().latitude + "";
            longitudeValue = bean.getLocation().longitude + "";
            tv_address.setText(bean.getName());
            et_address.setText(bean.getAddress());
        }
    }
}